package com.pu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.pu.constant.MessageConstant;
import com.pu.context.BaseContext;
import com.pu.dto.*;
import com.pu.entity.*;
import com.pu.exception.AddressBookBusinessException;
import com.pu.exception.OrderBusinessException;
import com.pu.exception.ShoppingCartBusinessException;
import com.pu.mapper.AddressBookMapper;
import com.github.pagehelper.Page;
import com.pu.utils.HttpClientUtil;
import com.pu.utils.WeChatPayUtil;
import com.pu.mapper.UserMapper;
import com.pu.websocket.WebSocketServer;

import com.pu.mapper.OrderDetailMapper;
import com.pu.mapper.OrderMapper;
import com.pu.mapper.ShoppingCartMapper;
import com.pu.result.PageResult;
import com.pu.service.OrderService;
import com.pu.service.ShoppingCartService;
import com.pu.vo.OrderPaymentVO;
import com.pu.vo.OrderStatisticsVO;
import com.pu.vo.OrderSubmitVO;
import com.pu.vo.OrderVO;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Yusc
 * @Date 2023/11/1 18:35
 * @Version
 * @Description C端：订单管理
 **/
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    //    @Autowired
//    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

/*    @org.springframework.beans.factory.annotation.Value("${pu.shop.address}")
    private String shopAddress;

    @org.springframework.beans.factory.annotation.Value("${pu.baidu.ak}")
    private String ak;*/


    /**
     * @param ordersSubmitDTO 前端提交的数据
     * @auther: Yusc
     * @date 2023/11/2 12:43
     * @Description 用户下单
     */
    @Override
    @Transactional //开启事务
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 1、异常情况的处理（收货地址为空、超出配送范围、购物车为空等）
        // 查看收货地址
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 2、检查用户的收货地址是否超出配送范围
//        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        Long userId = BaseContext.getCurrentId();
        // 查看购物车（通过用户id查）
        List<ShoppingCart> shoppingCartList = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, userId)
                .list();
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //2.1、构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        //2.2、向订单表中插入1条数据
        orderMapper.insert(order);

        // 3.1、订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        // 3、向订单明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 4、清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 5、封装返回结果
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }

    /**
     * @auther: Yusc
     * @date 2023/11/4 16:36
     * @Description 用户端订单分页查询
     */
    @Override
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();
        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<OrderDetail>()
                        .eq(OrderDetail::getOrderId, orderId);
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * @param id 订单id
     * @auther: Yusc
     * @date 2023/11/4 17:42
     * @Description 查询订单详情
     */
    @Override
    public OrderVO details(Long id) {
        // 1、根据id查询订单
        Orders orders = orderMapper.selectById(id);
        // 2、查询该订单对应的菜品/套餐明细
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);
        // 3、将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);  // 属性拷贝
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * @param id 订单id
     * @auther: Yusc
     * @date 2023/11/4 17:51
     * @Description 用户取消订单
     */
    @Override
    public void userCancelById(Long id) throws Exception {
        // 1、根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 2、校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 3、订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 4、订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            /*weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 5、更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        // 6、根据订单id更新数据
        orderMapper.updateById(orders);
    }

    /**
     * @param id 订单id
     * @auther: Yusc
     * @date 2023/11/4 21:11
     * @Description 再来一单
     */
    @Override
    public void repetition(Long id) {
        // 1、查询当前用户id
        Long userId = BaseContext.getCurrentId();
        // 2、根据订单id查询当前订单详情
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);

        // 3、将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetails.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 3.1、将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 4、将购物车对象批量添加到数据库
        shoppingCartService.saveBatch(shoppingCartList);
    }

    /**
     * @auther: Yusc
     * @date 2023/11/4 21:30
     * @Description 管理端-订单分页搜索
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * @auther: Yusc
     * @date 2023/11/4 21:49
     * @Description 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 1、根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 2、将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * @auther: Yusc
     * @date 2023/11/4 23:34
     * @Description 订单支付 微信支付需要商家认证才能开通,所以只能模拟支付
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 1、获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        // 2、生成空jsonObject
        JSONObject jsonObject = new JSONObject();

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }

    /**
     * @param orderNumber 订单号
     * @auther: Yusc
     * @date 2023/11/4 23:41
     * @Description 模拟->支付成功，修改订单状态
     */
    @Override
    public void paySuccess(String orderNumber) {
        // 1、根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(orderNumber);
        // 2、根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        // 3、根据订单id更新订单信息
        orderMapper.updateById(orders);

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orderNumber);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * @auther: Yusc
     * @date 2023/11/5 0:12
     * @Description 接单
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())   // 获取订单id
                .status(Orders.CONFIRMED)   // 修改为已接单状态
                .build();
        orderMapper.updateById(orders);
    }

    /**
     * @auther: Yusc
     * @date 2023/11/5 11:18
     * @Description 拒单
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 1、根据id查订单
        Orders ordersDB = orderMapper.selectById(ordersRejectionDTO.getId());
        // 2、订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 3、支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (Objects.equals(payStatus, Orders.PAID)) {
            //用户已支付，需要退款
            log.info("申请退款,应退金额：{}", ordersDB.getAmount());
        }
        // 4、拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());     // 订单id
        orders.setStatus(Orders.CANCELLED); // 订单状态
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason()); //拒单原因
        orders.setCancelTime(LocalDateTime.now());  //更新时间
        // 5、根据订单id更新数据
        orderMapper.updateById(orders);
    }

    /**
     * @auther: Yusc
     * @date 2023/11/5 11:31
     * @Description 管理单：取消订单
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 1、根据id查询订单
        Orders ordersDB = orderMapper.selectById(ordersCancelDTO.getId());
        // 2、支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (Objects.equals(payStatus, Orders.PAID)) {
            //用户已支付，需要退款
            log.info("申请退款：{}", ordersDB.getAmount());
        }
        // 3、管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        // 4、根据订单id更新
        orderMapper.updateById(orders);
    }

    /**
     * @auther: Yusc
     * @date 2023/11/5 11:42
     * @Description 派送订单
     */
    @Override
    public void delivery(Long id) {
        // 1、根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 2、校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 3、更新订单状态,状态转为派送中
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        // 4、根据id更新订单
        orderMapper.updateById(orders);
    }

    /**
     * @auther: Yusc
     * @date 2023/11/5 11:56
     * @Description 完成订单
     */
    @Override
    public void complete(Long id) {
        // 1、根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 2、校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 3、更新订单状态,状态转为完成
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        // 4、根据id更新订单
        orderMapper.updateById(orders);
    }

    /**
     * @auther: Yusc
     * @date 2023/11/5 17:07
     * @Description 用户催单
     */
    @Override
    public void reminder(Long id) {
        // 1、查询订单是否存在
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 2、基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);     //2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * @param page 分页数据
     * @auther: Yusc
     * @date 2023/11/4 21:40
     * @Description 获取订单菜品信息
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * @param orders 订单数据
     * @auther: Yusc
     * @date 2023/11/4 21:32
     * @Description 根据订单id获取菜品信息字符串
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);

        // 将每一条订单菜品信息拼接为字符串（格式：冰渣豆花*3；）
        List<String> orderDishList = orderDetails.stream().map(
                x -> x.getName() + "*" + x.getNumber() + ";"
        ).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * @param address 地址
     * @auther: Yusc
     * @date 2023/11/5 17:29
     * @Description 检查客户的收货地址是否超出配送范围
     */
/*    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 20000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }*/
}
